# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "rufus-scheduler"

# This example filter will replace the contents of the default 
# message field with whatever you specify in the configuration.
#
# It is only intended to be used as an example.
class LogStash::Filters::W3t < LogStash::Filters::Base

  # Setting the config_name here is required. This is how you
  # configure this filter from your Logstash config.
  #
  # filter {
  #   w3t {
  #   }
  # }
  #
  config_name 'w3t'

  # status '打开': 1 '断开连接': 2 '关闭': 3

  public
  def register
    # Add instance variables
    @events_queue = SizedQueue.new(100)
    @status_map = Hash.new
    @last_event = Hash.new
  end # def register

  public
  def multi_filter(events)
    result = []
    events.each do |event|
      unless event.cancelled?
        filter(event)
      end
    end
    while !@events_queue.empty? do
      event = @events_queue.pop
      event.uncancel
      result << event
    end
    result
  end

  public
  def filter(event)
    # filter_matched should go in the last line of our successful code
    #
    filter_matched(event)
    host = event['host']
    @status_map[host] = Hash.new unless @status_map.has_key? host
    @last_event[host] = Hash.new unless @last_event.has_key? host

    if event['message'] == '连接断开'
      @status_map[host][event['c_no']] = 2
      @events_queue.push event
    else
      if event['message'] == '打开'
        @last_event[host].each {|c_no, event|
          if @status_map[host][c_no] == 3
            @events_queue.push event
            @status_map[host][c_no] = -1
          end
        }
        if @status_map[host][event['c_no']] == 2
        else
          @status_map[host][event['c_no']] = 1
          @events_queue.push event
        end
      elsif event['message'] == '关闭'
        @status_map[host][event['c_no']] = 3
      end
    end
    @last_event[host][event['c_no']] = event
  end # def filter
end # class LogStash::Filters::W3t
